package org.huanletao.ssm.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.huanletao.ssm.model.User;
import org.huanletao.ssm.service.LoginService;
import org.huanletao.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <p>
 * </p>
 * package: org.huanletao.ssm.realm
 * description:
 * className: UserRealm
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/8/27 10:59
 * since: 1.0.0
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = loginService.findUserByUserName(username);
        if (Objects.isNull(user))
            return null;
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }


}
